//
//  YRNetwoekTools.swift
//  新浪微博
//
//  Created by Viper on 16/6/26.
//  Copyright © 2016年 Viper. All rights reserved.
//

import UIKit
import AFNetworking
//请求方式枚举
enum MethodType : String {
    case GET = "GET"
    case POST = "POST"
}
class YRNetwoekTools: AFHTTPSessionManager {
    
    //全局访问点
    static let sharedTools : YRNetwoekTools = {
        
       let tools  = YRNetwoekTools()
        
         tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        
    }()
    
    //MARK: - 给成功的闭包和失败的闭包格式起别名
    
    typealias SuccessClosure = (response : AnyObject?)->()
    typealias FailureClosure = (error : NSError)->()
    
    
    
    func request(method:MethodType , urlString : String , parameters : AnyObject? , success : SuccessClosure , failure : FailureClosure){
        
        if method == .GET {
           self.GET(urlString, parameters: parameters, progress: nil, success: { (_, respones) in
            
            success(response: respones)
            
            }, failure: { (_, error) in
            
                failure(error: error)
                
           })
            
        }else{
            
            self.POST(urlString, parameters: parameters, progress: nil, success: { (_, respones) in
            success(response: respones)
                }, failure: { (_, error) in
                    failure(error: error)
            })
            
        }
        
        
    }

}

extension YRNetwoekTools {
    //请求token
    func oauthUserAccount (code : String , success : SuccessClosure , failure : FailureClosure){
        
        //请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数
        let params = [
            
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
            
        ]

        self.request(MethodType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
   
    }
    //请求个人信息数据
    func oauthLoadUserInfo(userAccount : YRUserAccount , success : SuccessClosure , failure : FailureClosure ){
        //请求url
        let url = "https://api.weibo.com/2/users/show.json"
        //请求参数
        let params = [
            
            "access_token" : userAccount.access_token!,
            
            "uid" : userAccount.uid!
        
        ]
        
        self.request(MethodType.GET, urlString: url, parameters: params, success: success, failure: failure)
        
    }
    
}
///MARK: - 请求首页数据
extension YRNetwoekTools{
    
    func homeLoadStatusData(sinceId : Int64,maxId : Int64, success : SuccessClosure , failure : FailureClosure){
        
        //请求url
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        //请求参数
        let params = [
            "access_token" : YRUserAccountTools.sharedTools.accessToken!,
            "since_id" : "\(sinceId)",
            "max_id" : "\(maxId)"
        ]
        //发送请求
        request(.GET, urlString: urlString, parameters: params, success: success, failure: failure)
                
        }
        
    }

//发布微博界面
extension YRNetwoekTools{
    
    func composeUpdate(status: String, success: SuccessClosure, failure: FailureClosure){        //请求URL
        let url = "https://api.weibo.com/2/statuses/update.json"
        //请求参数
        let params = [
            
            "access_token" : YRUserAccountTools.sharedTools.accessToken!,
            "status" : status
        ]

         request(.POST, urlString: url, parameters: params, success: success, failure: failure)
        
    }
    func comoposeUpload(status: String,imageList:[UIImage], success: (response: AnyObject?)->(), failure:(error: NSError)->() ){
        // 请求url
        let URLString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数
        let params = [
            "access_token":YRUserAccountTools.sharedTools.accessToken!,
            "status":status
            
        ]
        POST(URLString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            // 以表单形式提交（拼接到表单后面提交）
            /*
             data : 将要上传到服务器的二进制文件
             name : 服务器要求规定好文件名称(协议)
             fileName:  上传文件完成后保存到服务器的文件路径 （新浪微博不需要你指定 都会按着自己的方式保存到响应的文件夹中）--- 随意传
             mimeType: 指定上传的二进制文件的格式 application/octet-stream 忽略上传文件的格式
             如果指定为图片 image/jpeg （大类型/ 小类型）
             */
            
            // 遍历数组
            for image in imageList {
                // image 转二进制
                let data = UIImagePNGRepresentation(image)!
                
                formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                
                success(response: response)
                
        }) { (_, error) -> Void in
            failure(error: error)
        }
        
  
        
    }
    
 
}


